from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging
from app.core.config import settings
from app.core.database import db
from app.api.api import api_router

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("Starting up...")
    await db.connect()
    yield
    logger.info("Shutting down...")
    await db.disconnect()

app = FastAPI(
    title="精灵虚拟物品管理系统",
    description="精灵书籍投喂管理API",
    version="1.0.0",
    lifespan=lifespan
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(api_router, prefix=settings.api_prefix)

@app.get("/")
async def root():
    return {
        "message": "精灵虚拟物品管理系统",
        "version": "1.0.0",
        "status": "running"
    }

@app.get("/health")
async def health_check():
    try:
        async with db.pg_pool.acquire() as conn:
            await conn.fetchval("SELECT 1")
        
        mongo_db = db.get_mongo_db()
        await mongo_db.command("ping")
        
        redis_status = "connected"
        if db.redis_client:
            await db.redis_client.ping()
        else:
            redis_status = "not configured"
        
        return {
            "status": "healthy",
            "postgres": "connected",
            "mongodb": "connected",
            "redis": redis_status
        }
    except Exception as e:
        logger.error(f"Health check failed: {e}")
        return {
            "status": "unhealthy",
            "error": str(e)
        }